package blog.service;

import blog.dao.ArticleRespository;
import blog.dao.ArticletypeRespository;
import blog.entity.Article;
import blog.entity.Articletype;
import jakarta.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Transactional
public class ArticleService {
    @Autowired
    ArticleRespository articleRespository;
    @Autowired
    ArticletypeRespository articletypeRespository;

    /**
     * 查找所有
     * 
     * @return
     */
    public List<Article> findAll()  {
	return articleRespository.findAll();
    }

    /**
     * 分页查找
     * 
     * @return
     */
    public Page<Article> findAllByPage(int pageIndex, int pageSize) {
	//排序
	Sort sort = Sort.by(Sort.Direction.DESC, "id");
	//分页
	Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
	//分页查询
	Page<Article> articlePage = articleRespository.findAll(pageable);
	return articlePage;
    }

    /**
     * 那name分页查找
     * 
     * @return
     */
    public Page<Article> pageArticleByType(String name, int pageIndex, int pageSize) {
	//排序
	Sort sort = Sort.by(Sort.Direction.ASC, "id");
	//分页
	Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
	//分页查询
	Page<Article> articlePage = articleRespository.findByTitle(name, pageable);
	return articlePage;
    }

    /**
     * 根据Name查找所有，升序
     * 
     * @return
     */
    public List<Article> findByTitleLike(String title) {
	return articleRespository.findByTitleLike(title);
    }
    
    /**
     * 保存分类
     * 
     * @param article
     * @return
     */
    public Article save(Article article) {
	return articleRespository.save(article);
    }
    
    /**
     * 查找某条记录
     * 
     * @param id
     * @return
     */
    public Article findById(long id) {
	return articleRespository.findById(id).orElse(new Article());
    }

    /**
     * 删除某条记录
     * 
     * @param id
     */
    public void deleteById(long id) {
	articleRespository.deleteById(id);
    }



    public void updateById(String type, long id) {
	articletypeRespository.updateById(type, id);
    }
}
